import _ from 'lodash';
import apiConfig from '@/api/config';
import user from '@/api/user/index';
import auth from '@/utils/auth';

export const SET_MODEL = 'SET_MODEL';

export default {
  namespaced: true,
  state: {
    models: {}
  },

  mutations: {
    [SET_MODEL]: function(state, model) {
      state.models[model.account.user_id] = model;
    }
  },

  actions: {
		login(context, payload) {
			apiConfig.remove();
			return user.login(payload).then(function(res) {
				if(res) {
					auth.setToken(res.token);
					return res;
				}
				return false;
			});
		},
    findFirstById(context, id) {
      return user.findFirstById(id).then(function(res) {
        if(res !== false && typeof(res.model) !== 'undefined' && res.model !== '') {
          //context.commit(SET_MODEL, res.model);
          return res.model;
        }

        return false;
      });
    },
    update(context, payload) {
      let data = _.clone(payload.data);
      _.unset(data, 'n_account');
      _.unset(data, 'p_account');
      _.unset(data, 's_account');

      return user.update(payload.id, data);
    }
  },

  getters: {
    findFirstById(state, id) {
      return state.models[id];
    }
  }
};
